package metier;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import DB.Request;
import bean.Classe;
import bean.Formateur;
import bean.Matiere;
import bean.Repertoires;

public class ClasseMetier {
	private static ClasseMetier singleton = new ClasseMetier();
	
	public static ClasseMetier getInstance(){
		return singleton;
	}
	
	public Classe save(Classe classe){
		if(classe != null){
			String query;
			if (classe.getId_classe() != null) {
				//UPDATE
				query = "UPDATE classe SET libelle=? WHERE id_classe=" + classe.getId_classe();
			} else {
				//INSERT
				query = "INSERT INTO classe(libelle) VALUES (?)";
			}
			List<Object> param = new ArrayList<Object>();
			param.add(classe.getLibelle());
			Request.getInstance().executeUpdate(query, param);

		}
		if (classe.getId_classe() != null) {
			return getById(classe.getId_classe());
		} else {
			return getById(getLastId());
		}
		
	}
	
	public void delete(Classe classe){
		String query = "DELETE FROM classe WHERE id_classe=" + classe.getId_classe();
		Request.getInstance().executeUpdate(query);
	}
	
	public Classe getById(Integer id){
		Classe classe = null;
		String query = "SELECT * FROM classe WHERE id_classe=" + id;
		ResultSet resultat = Request.getInstance().executeQuery(query);
		try {
			while(resultat.next()){
				classe = new Classe(id, resultat.getString("libelle"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return classe;
	}
	
	public List<Classe> getAll(){
		List<Classe> classes = new ArrayList<Classe>();
		String query = "SELECT * FROM classe";
		ResultSet resultat = Request.getInstance().executeQuery(query);
		try {
			while(resultat.next()){
				Classe classe = new Classe(resultat.getInt("id_classe"), resultat.getString("libelle"));
				classes.add(classe);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return classes;
	}
	
	private Integer getLastId(){
		Integer result = null;
		String query = "SELECT max(id_classe) AS id_classe FROM classe";
		ResultSet resultat = Request.getInstance().executeQuery(query);
		try {
			while(resultat.next()){
				result = resultat.getInt("id_classe");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}


}
